<template>
  <view class="page-container" :class="{popupShow:showPopup}">
    <view class="test-container">
      <view class="test-info">
        <view>
          <view class="test-type">{{questionType[question.qtype]}}</view>
          <view class="test-progress"><text>{{questionIndex+1}}</text>/{{questionList.length}}</view>
        </view>
        <view class="test-time">
          <u-icon :label="countdownStr" labelPos="left" labelSize="28rpx" labelColor="#323232" space="16rpx"
            width="24rpx" height="38rpx" name="../../static/jk.png"></u-icon>
        </view>
      </view>
      <view class="test-card test-content">
        <view class="test-text">{{questionIndex+1}}.<view class="test-text-score">2分</view>
          {{question.topic}}
        </view>
        <view class="test-image">

        </view>
        <view class="test-answer-area">
          <view class="test-choice" v-if="question.qtype == 1 || question.qtype == 2 || question.qtype == 3">
            <view class="test-options-item" :class="question.userAnswer === item.id ? 'selected' : ''"
              v-for="(item,index) in question.options" :key="item.id" @click="onSelectSingle(item)">
              <view>{{optionDesc[index]}}</view>
              <view>{{item.optionText}}</view>
            </view>
          </view>
          <!-- <view class="test-short-answer">
            <u--textarea v-model="questionList[questionIndex].value" placeholder="请输入内容"></u--textarea>
          </view> -->
          <!-- <view>
            <view class="test-options-item selected">
              <view>A</view>
              <view>是</view>
            </view>
            <view class="test-options-item">
              <view>B</view>
              <view>否</view>
            </view>
          </view> -->
          <!-- <view>
            <u--input placeholder="请输入内容" border="surround" v-model="questionList[questionIndex].value"
              @change="change"></u--input>
          </view> -->
        </view>
      </view>
      <view class="test-card test-corrent-answer" v-if="showParse">
        <view class="test-card-title">答案</view>
        <view class="corrent-answer-content">
          <view>正确答案：<text style="color: #07A773;">{{correctAnswer}}</text></view>
          <view>你的答案：<text style="color: #FF3649;">{{userAnswer}}</text></view>
        </view>
      </view>
      <view class="test-card test-parse" v-if="showParse">
        <view class="test-card-title">解析</view>
        <view class="test-parse-content">
          <view style="color: #646464;">{{question.analysis}}</view>
          <view>
            <video v-if="quesion.analysisType === 'video'" :src="quesion.analysisTypeFile" controls></video>
            <image v-if="quesion.analysisType === 'image'" mode="widthFix" :src="quesion.analysisTypeFile"></image>
            <audio v-if="quesion.analysisType === 'audio'" :src="quesion.analysisTypeFile" controls></audio>
          </view>
          <view class="test-knowledge-content">
            <view class="test-knowledge-title">知识点</view>
            <view class="test-knowledge-list">
              <view>图定运行的规律</view>
              <view>列车时刻表调整的规律</view>
            </view>
          </view>
          <u-divider text="本题有1022人做过，146人做错" textSize="22rpx"></u-divider>
        </view>
      </view>
      <view class="test-card test-related" v-if="showParse">
        <view class="test-card-title">相关知识点题</view>
        <view class="test-related-desc">
          图定客车（空车底）运行时刻调整，长 沙~北京西Z2次，北京西终到时刻由 8:00调整为（）。
        </view>
        <view>

        </view>
        <view>答案：<text>新的列车时刻表调整</text></view>
      </view>
    </view>
    <view class="action-bar">
      <view @click="onPrev">
        <u-icon label="上一题" labelPos="bottom" labelSize="22rpx" labelColor="#969696" space="16rpx" size="40rpx"
          name="../../static/training/up.png"></u-icon>
      </view>
      <view @click="onJumpAnswer">
        <u-icon label="答题卡" labelPos="bottom" labelSize="22rpx" labelColor="#969696" space="16rpx" size="40rpx"
          name="../../static/training/dtk.png"></u-icon>
      </view>
      <view @click="onViewParse">
        <u-icon label="解析" labelPos="bottom" labelSize="22rpx" labelColor="#969696" space="16rpx" size="40rpx"
          name="../../static/training/jiexi.png"></u-icon>
      </view>
      <view @click="onNext">
        <u-icon label="下一题" labelPos="bottom" labelSize="22rpx" labelColor="#969696" space="16rpx" size="40rpx"
          name="../../static/training/next.png"></u-icon>
      </view>
    </view>
    <u-popup :show="showPopup" :closeable="true" @close="closePopup" customStyle="background:#F2F3F6;"
      class="answer-card-popup">
      <AnswerCard :questions="questionList" @select="onSelectQuestion" @submit="onSubmit" />
    </u-popup>
  </view>
</template>

<script>
  import dayjs from 'dayjs';
  import duration from 'dayjs/plugin/duration';
  import { showSuccess } from '@/utils/app.js';
  import {
    getExamListData,
    submitExamPaper
  }
  from "@/common/api/exam/exam.js";
  import AnswerCard from './answer_card.vue'

  dayjs.extend(duration);

  export default {
    data() {
      return {
        showPopup: false,
        showParse: false,
        countdown: null,
        countdownInterval: null,
        questionIndex: 0,
        questionList: [{
          value: '1',
          qtype: '1',
        }],
        paperInfo: {},
        questionType: {
          1: '单选',
          2: '多选',
          3: '判断',
          4: '填空',
          5: '简答'
        },
        optionDesc: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      }
    },
    components: {
      AnswerCard
    },
    onLoad(option) {
      this.getExamList(option.id);
      // this.countdown = dayjs.duration({
      //   seconds: 0,
      //   minutes: 90,
      // });
      // this.countdownInterval = setInterval(() => {
      //   if (this.countdown.asSeconds() === 0) {
      //     console.log('finished');
      //     clearInterval(this.countdownInterval);
      //   }
      //   this.countdown = this.countdown.subtract(1, 'seconds')
      // }, 1000)
    },
    computed: {
      countdownStr() {
        if (this.countdown) {
          return `${Math.floor(this.countdown.asMinutes())}'${this.countdown.seconds()}''`
        } else {
          return `0'00'`
        }

      },
      question() {
        return this.questionList[this.questionIndex]
      },
      correctAnswer() {
        if (this.question.qtype == 1 || this.question.qtype == 2 || this.question.qtype == 3) {
          const idx = this.question.options.findIndex(quest => quest.id === this.question.isCorrect)
          return idx < 0 ? '无' : this.optionDesc[idx]
        } else {
          return this.question.isCorrect
        }
      },
      userAnswer() {
        if (this.question.qtype == 1 || this.question.qtype == 2 || this.question.qtype == 3) {
          const idx = this.question.options.findIndex(quest => quest.id === this.question.userAnswer)
          return idx < 0 ? '无' : this.optionDesc[idx]
        } else {
          return this.question.isCorrect
        }
      }
    },
    methods: {
      getExamList(id) {
        getExamListData({
          id: id
        }).then(res => {
          const nowTime = dayjs();

          // console.log(nowTime.format('YYYY-MM-DD HH:mm:ss'), examFinishTime, Math.ceil(dayjs(examFinishTime).diff(nowTime,
          // 'minute',true)));
          let examFinishTime = uni.getStorageSync(res.data.id);

          console.log(examFinishTime)

          if (!examFinishTime) {
            examFinishTime = nowTime.add(dayjs.duration(60, 'minutes')).format('YYYY-MM-DD HH:mm:ss');
            uni.setStorageSync(res.data.id, examFinishTime)
          }

          this.countdown = dayjs.duration({
            seconds: 0,
            minutes: Math.ceil(dayjs(examFinishTime).diff(nowTime, 'minute', true)),
          });
          this.questionList = res.data.quests;
          this.paperInfo = res.data;
          this.countdownInterval = setInterval(() => {
            if (this.countdown.asSeconds() === 0) {
              console.log('finished');
              clearInterval(this.countdownInterval);
            }
            this.countdown = this.countdown.subtract(1, 'seconds')
          }, 1000)
        })
      },
      onJumpAnswer() {
        this.showPopup = true;
      },
      onViewParse() {
        this.showParse = true;
      },
      onJumpRecord() {
        uni.navigateTo({
          url: "/pages/exam/record"
        })
      },
      onNext() {
        this.showParse = false;
        if (this.questionIndex >= this.questionList.length - 1) {
          this.questionIndex = this.questionList.length - 1;
          this.onJumpAnswer()
        } else {
          this.questionIndex++;
        }
      },
      onPrev() {
        this.showParse = false;
        if (this.questionIndex <= 0) {
          this.questionIndex = 0;
        } else {
          this.questionIndex--;
        }
      },
      onSelectQuestion(id) {
        this.questionIndex = this.questionList.findIndex(quest => quest.id === id);
        this.showPopup = false;
      },
      closePopup() {
        this.showPopup = false;
      },
      onSelectSingle(data) {
        this.$set(this.questionList, this.questionIndex, {
          ...this.questionList[this.questionIndex],
          isAnswer: 'y',
          userAnswer: data.id,
        })
      },
      onSubmit() {
        const answers = this.questionList.map(quest => {
          return {
            id: quest.id,
            questId: quest.questId,
            qtype: quest.qtype,
            isAnswer: quest.isAnswer,
            userAnswer: quest.userAnswer,
            options: quest.options.map(opt => {
              return {
                id: opt.id,
                userAnswer: opt.userAnswer
              }
            })
          }
        });

        uni.removeStorageSync(this.paperInfo.id)
        submitExamPaper({
          id: this.paperInfo.id,
          userId: this.paperInfo.userId,
          quests: answers
        }).then(res => {
          showSuccess('试卷提交成功', () => {
            uni.navigateTo({
              url: `/pages/exam/grades?id=${this.paperInfo.id}&examId=${this.paperInfo.examId}`
            })
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page-container {
    background-color: #f2f3f6;
    min-height: 100%;
  }

  .test-container {
    padding: 0 4%;
    padding-bottom: 200rpx;

    &.popupShow {
      position: fixed;
      overflow: hidden;
    }
  }

  .test-info {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 20rpx;
  }

  .test-type {
    padding: 6rpx 16rpx;
    color: #3772F5;
    background: rgba(26, 99, 255, 0.1);
    border-radius: 8rpx;
    display: inline-block;
    font-size: 22rpx;
  }

  .test-progress {
    display: inline-block;
    margin-left: 10rpx;
    color: #969696;
    font-size: 26rpx;

    text {
      color: #323232;
      font-size: 28rpx;
    }
  }

  .test-time {
    font-size: 28rpx;
    color: #323232;
  }

  .test-card {
    padding: 40rpx 30rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
  }

  .test-card-title {
    font-weight: bold;
    font-size: 34rpx;
    color: #222222;
  }

  .test-content {}

  .test-text {
    color: #323232;
    font-size: 36rpx;
    font-weight: bold;
    letter-spacing: 4rpx;
    line-height: 60rpx;
  }

  .test-text-score {
    display: inline-block;
    background-color: #FF3649;
    padding: 5rpx 16rpx;
    color: #fff;
    border-radius: 6rpx;
    margin: 0 8rpx;
    font-size: 22rpx;
    font-weight: normal;
    vertical-align: middle;
    line-height: normal;
  }

  .test-answer-area {
    margin-top: 50rpx;
  }

  .test-options-item {
    padding: 36rpx 40rpx;
    font-size: 32rpx;
    color: #323232;
    background: rgba(200, 200, 200, 0.2);
    border-radius: 12rpx;
    font-weight: bold;
    margin-bottom: 20rpx;

    >view {
      display: inline-block;
    }

    >view:first-child {
      padding: 0 40rpx;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 6px;
        display: block;
        background-color: #DAD8D8;
        width: 1px;
        height: 22rpx;
      }
    }

    view:last-child {
      padding: 0 30rpx;
    }

    &.selected {
      color: #1A63FF;
      background: rgba(26, 99, 255, 0.2);

      >view:first-child {
        &::after {
          background-color: #1A63FF;
        }
      }
    }
  }

  .test-parse-content {
    margin-top: 30rpx;
  }

  .action-bar {
    position: fixed;
    bottom: 0;
    width: 100%;
    display: flex;
    text-align: center;
    padding: 30rpx;
    background-color: #fff;
    color: #969696;

    >view {
      flex: 1;
    }
  }

  .corrent-answer-content {
    display: flex;
    background: #F2F3F6;
    border-radius: 16rpx;
    padding: 40rpx 30rpx;
    margin-top: 20rpx;
    text-align: center;

    text {
      font-weight: bold;
    }

    >view {
      flex: 1;
    }
  }

  .test-knowledge-content {
    margin-bottom: 50rpx;
  }

  .test-knowledge-title {
    color: #323232;
    font-size: 32rpx;
    font-weight: bold;
    margin-top: 50rpx;
  }

  .test-knowledge-list {
    margin-top: 30rpx;

    >view {
      padding: 26rpx 30rpx;
      background: rgba(255, 107, 0, 0.1);
      border-radius: 10rpx;
      color: #FF6B00;
      margin-bottom: 20rpx;

      &::before {
        content: '';
        display: inline-block;
        width: 8rpx;
        height: 8rpx;
        border-radius: 50%;
        background-color: #FF6B00;
        vertical-align: middle;
        margin-right: 30rpx;
      }
    }
  }

  .answer-card-popup {
    ::v-deep .u-popup__content__close--top-right {
      right: 5px;
      top: 10px;
    }
  }
</style>